package com.example.librarymanagementproject2.mq;

import com.example.librarymanagementproject2.Common.config.RabbitConfig;
import com.example.librarymanagementproject2.converter.UserConverter;
import com.example.librarymanagementproject2.model.document.UserDocument;
import com.example.librarymanagementproject2.model.entity.User;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;


/**
 * @ClassName LoginConsumer
 * @Description TODO
 * @Author Kx
 * @Date 2025/10/22 20:12
 * @Version 1.0
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class LoginConsumer {
    private final ElasticsearchOperations elasticsearchOperations;
    private final UserConverter userConverter;

    /**
     * @author: kx
     * @date: 2025/10/22 20:16
     * @param user : 用户信息
     * @description: 消费用户登录
    */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = RabbitConfig.USER_LOGIN_QUEUE, durable = "true"),
            exchange = @Exchange(name = RabbitConfig.USER_EXCHANGE, type = ExchangeTypes.DIRECT),
            key = RabbitConfig.USER_LOGIN_ROUTING_KEY
    ))
    public void receive(User user) {
        user.setUpdateTime(null);
        user.setCreateTime(LocalDateTime.now());
        user.setCancelTime(null);
        // 把用户信息转换成用户文档信息
        UserDocument userDocument = userConverter.toUserDocument(user);
        // 添加用户文档信息
        elasticsearchOperations.save(userDocument);
    }
}
